// 模拟地址数据
let addressList = [
  {
    id: '1',
    name: '张三',
    phone: '13800138000',
    province: '广东省',
    city: '深圳市',
    district: '南山区',
    detail: '科技园南区T3栋502室',
    isDefault: true
  },
  {
    id: '2',
    name: '李四',
    phone: '13900139000',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    detail: '建国路88号现代城5号楼1单元801',
    isDefault: false
  }
]

/**
 * 获取地址列表
 */
export function getAddressList() {
  return {
    code: 0,
    message: '成功',
    data: addressList
  }
}

/**
 * 添加地址
 */
export function addAddress(data) {
  const newAddress = {
    ...data,
    id: Date.now().toString()
  }
  
  // 如果设为默认地址，其他地址取消默认
  if (newAddress.isDefault) {
    addressList.forEach(addr => {
      addr.isDefault = false
    })
  }
  
  addressList = [newAddress, ...addressList]
  
  return {
    code: 0,
    message: '添加成功',
    data: newAddress
  }
}

/**
 * 更新地址
 */
export function updateAddress(data) {
  const index = addressList.findIndex(addr => addr.id === data.id)
  
  if (index !== -1) {
    // 如果设为默认地址，其他地址取消默认
    if (data.isDefault) {
      addressList.forEach(addr => {
        if (addr.id !== data.id) {
          addr.isDefault = false
        }
      })
    }
    
    addressList[index] = { ...data }
    
    return {
      code: 0,
      message: '更新成功',
      data: addressList[index]
    }
  }
  
  return {
    code: 1,
    message: '地址不存在',
    data: null
  }
}

/**
 * 删除地址
 */
export function deleteAddress(id) {
  const initialLength = addressList.length
  addressList = addressList.filter(addr => addr.id !== id)
  
  if (addressList.length < initialLength) {
    return {
      code: 0,
      message: '删除成功',
      data: null
    }
  }
  
  return {
    code: 1,
    message: '地址不存在',
    data: null
  }
}

/**
 * 设置默认地址
 */
export function setDefaultAddress(id) {
  const address = addressList.find(addr => addr.id === id)
  
  if (address) {
    addressList.forEach(addr => {
      addr.isDefault = addr.id === id
    })
    
    return {
      code: 0,
      message: '设置成功',
      data: null
    }
  }
  
  return {
    code: 1,
    message: '地址不存在',
    data: null
  }
}